package com.asia5b.a5mall.shop.activity

import android.os.Bundle
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import android.view.View
import android.view.ViewTreeObserver
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.A5BMallConfigCenter
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.event.CollectGoodsChange
import com.asia5b.a5mall.middleware.event.CollectShopChange
import com.asia5b.a5mall.middleware.event.LoginEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.shop.ShopActivityVM
import com.asia5b.a5mall.middleware.model.bean.ShopMenuBean
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import com.asia5b.a5mall.middleware.model.shop.ShopCollectModel
import com.asia5b.a5mall.middleware.model.shop.ShopGoodsInfoModel
import com.asia5b.a5mall.middleware.base.BaseFragmentPagerAdapter
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.MenuPopWindow
import com.asia5b.a5mall.shop.R
import com.asia5b.a5mall.shop.databinding.ActivityShopBinding
import com.asia5b.a5mall.shop.fragment.ShopAllFragment
import com.asia5b.a5mall.shop.fragment.ShopHomeFragment
import com.asia5b.a5mall.shop.fragment.ShopTagFragment
import com.google.android.material.appbar.CollapsingToolbarLayout
import kotlinx.android.synthetic.main.activity_shop.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   店铺页面
 */
@Route(path = ActCons.ShopActivity)
class ShopActivity : SimpleActivity<ShopActivityVM, ActivityShopBinding>() {
    override val viewModelClazz: Class<ShopActivityVM>
        get() = ShopActivityVM::class.java

    override fun getDataBinding(): ActivityShopBinding {
        shopId = intent.getIntExtra("shopId", 0)
        return ActivityShopBinding.inflate(layoutInflater)
    }

    /**
     * @Name  menuView
     * @Type  MenuPopWindow
     * @Note  菜单PopWindow
     */
    private val menuView by lazy {
        MenuPopWindow.build(this, ArrayList<ShopMenuBean>().then { self ->
            self.add(ShopMenuBean(getString(R.string.商品_首页), R.drawable.ic_home_white, 1))
            //todo 这里是分享店铺地址.如果微信打开后,会自动弹出小程序端,暂时屏蔽吧
            self.add(ShopMenuBean(getString(R.string.分享), R.drawable.ic_share_white, 2))
            self.add(ShopMenuBean(getString(R.string.店铺详情), R.drawable.ic_shop_white, 3))
        }).setItemCallBack { item ->
            when (item.menuId) {
                1 -> {
                    push(ActCons.MainActivity)
                }
                2 -> {
                    mViewModel.share(mActivity,
                            A5BMallConfigCenter.INSTANCE.WAP_SELLER_URL + "$shopId",
                            shopModel!!.absShopLogo
                                    ?: "", getString(R.string.武时亿商城), shopModel!!.absShopName)
                }
                3 -> {
                    push(ActCons.ShopDetailActivity, { postcard ->
                        postcard.withInt("shopId", shopId)
                    })
                }
            }
        }
    }


    val tabTexts by lazy {
        arrayListOf<String>(
                getString(R.string.商品_首页),
                getString(R.string.全部),
                getString(R.string.热销),
                getString(R.string.上新),
                getString(R.string.推荐)
        )
    }
    val tab by lazy { tab_shop }
    val mViewPager by lazy { vp_shop }
    val fragments = arrayListOf<Fragment>()


    var shopId: Int = 0

    var shopModel: AbsShopModel? = null
    var shopCollectModel: ShopCollectModel? = null

    override fun initView() {
        fragments.clear()
        var bundel = Bundle()
        bundel.putInt("shopId", shopId)
        fragments.add(sNewStanceFragment(mActivity, ShopHomeFragment::class.java, bundel))
        bundel = Bundle()
        bundel.putInt("shopId", shopId)
        fragments.add(sNewStanceFragment(mActivity, ShopAllFragment::class.java, bundel))
        for (shopTag in 0..2) {
            bundel = Bundle()
            bundel.putInt("shopId", shopId)
            bundel.putInt("shopTag", shopTag)
            fragments.add(sNewStanceFragment(mActivity, ShopTagFragment::class.java, bundel))
        }
        mViewPager.adapter = BaseFragmentPagerAdapter(supportFragmentManager, fragments, tabTexts)
        tab.setupWithViewPager(mViewPager)
        mViewPager.offscreenPageLimit = fragments.size

        setCollectionView()


    }

    fun setCollectionView() {
        val isCollection = shopCollectModel?.message ?: false
        iv_shopdetail_collecticon.isSelected = isCollection
        iv_shopdetail_collecticon.text = (isCollection).judge(getString(R.string.已关注), ResString.addCollect())
    }

    var globalListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    override fun initEvent() {
        /*需要重新定义高度*/
        val layoutParams = shop_top_lay.layoutParams as CollapsingToolbarLayout.LayoutParams
        //37f表示搜索控件的高度
        layoutParams.height = DisplayUtils.getStatusHeight(mActivity) + DisplayUtils.dip2px(mActivity, 37f)
        shop_top_lay.layoutParams = layoutParams

        /*需要重新定义高度*/
        globalListener = object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                cons_shop_search_vessel.viewTreeObserver.removeOnGlobalLayoutListener(globalListener)
                val layoutParams1 = appbar_shop.layoutParams as CoordinatorLayout.LayoutParams
                layoutParams1.height = shop_top_lay.height + cons_shop_search_vessel.height
                appbar_shop.layoutParams = layoutParams1
            }
        }
        cons_shop_search_vessel.viewTreeObserver.addOnGlobalLayoutListener(globalListener)

        //领取优惠券
        iv_shop_coupon.setOnClickListener {
            push(ActCons.CouponHallActivity)
        }
        //店铺详情  postcard.withInt("shopId", shopId)
        val detailListener = View.OnClickListener {
            push(ActCons.ShopDetailActivity, { postcard ->
                postcard.withInt("shopId", shopId)
            })
        }
        tv_shopdetail_shopname.setOnClickListener(detailListener)
        iv_shopdetail_shopimg.setOnClickListener(detailListener)
        iv_shopdetail_collectnum.setOnClickListener(detailListener)
        //热门分类
        /*
                    push(ActCons.ShopCategoryActivity, { postcard ->
                postcard.withInt("shopId", shopId)
            })

         */
        //搜索
        ll_shop_search.setOnClickListener {
            push(ActCons.ShopSearchGoodsActivity, { postcard ->
                postcard.withInt("shopId", shopId)
                postcard.withString("keyword", "")
            })
        }
        //分类 push(ActCons.CouponHallActivity)
        //更多分享
        tv_shop_more.setOnClickListener {
            menuView.show(it)
        }
        //收藏店铺
        iv_shopdetail_collecticon.setOnClickListener {
            if (UserRepository.isLogin(mActivity)) {
                mViewModel.collectShop(shopModel?.absShopId ?: 0, shopCollectModel?.message
                        ?: false)
            }
        }


    }

    override fun startObserver() {
        mViewModel.collectShopResultLiveData.observe(this, Observer {
            collectShopResult(it)
        })
        mViewModel.getShopDetailResultLiveData.observe(this, Observer {
            getShopDetailResult(it)
        })
        mViewModel.isCollectShopResultLiveData.observe(this, Observer {
            isCollectShopResult(it)
        })
    }

    override fun initData() {
        mViewModel.getShopDetail(shopId)


    }

    fun collectShopResult(collect: Boolean) {
        shopCollectModel?.message = !collect
        setCollectionView()
        getEventBus().post(CollectGoodsChange())
    }

    fun getShopDetailResult(data: Array<Any>) {
        shopModel = data[0] as AbsShopModel
        shopCollectModel = data[1] as ShopCollectModel
        mDataBinding.shopModel = shopModel
//        mDataBinding.shopGoodsInfoModel = data[2] as ShopGoodsInfoModel
        setCollectionView()
        //背景图
        WImageLoader.displayImage(shopModel!!.absShopBackImg, iv_shop_shopbg, R.drawable.shape_shop_nobanner)

    }

    fun isCollectShopResult(data: ShopCollectModel) {
        shopCollectModel = data
        setCollectionView()
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCollectShopChange(it: CollectShopChange) {
        if (it.shopId == shopId) {
            shopCollectModel?.message = it.newCollectState
            setCollectionView()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(it: LoginEvent) {
        mViewModel.isCollectShop(shopId)
    }
}